package com.advertisementsystem.Controller;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.Servie.NotificationService;
import com.advertisementsystem.entity.Notification;

import com.advertisementsystem.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/notifications")
@RequiredArgsConstructor
public class NotificationsController {
    @Autowired
    private  NotificationService notificationService;

    /**
     * 获取当前用户的消息列表
     */
    @GetMapping
    public ResponseResult<IPage<Notification>> getNotifications(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String type,
            @RequestParam(required = false) Integer read) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long currentUserId = loginUser.getUser().getId();  // 获取当前登录用户ID

        Page<Notification> page = new Page<>(pageNum, pageSize);

        IPage<Notification> result = notificationService.getNotificationList(
                page, currentUserId, type, read);

        return ResponseResult.success(result);
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/{id}/read")
    public ResponseResult<Boolean> markAsRead(@PathVariable("id") Long id) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long currentUserId = loginUser.getUser().getId();  // 获取当前登录用户ID

        log.info("用户(ID:{})标记消息为已读, 消息ID:{}", currentUserId, id);

        boolean success = notificationService.markAsRead(id, currentUserId);

        if (success) {
            return ResponseResult.success(true);
        } else {
            return ResponseResult.error("标记已读失败");
        }
    }

    /**
     * 标记所有消息为已读
     */
    @PutMapping("/read-all")
    public ResponseResult<Boolean> markAllAsRead() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long currentUserId = loginUser.getUser().getId();  // 获取当前登录用户ID

        boolean success = notificationService.markAllAsRead(currentUserId);

        if (success) {
            return ResponseResult.success(true);
        } else {
            return ResponseResult.success(true); // 即使没有未读消息，也返回成功
        }
    }

    /**
     * 删除消息
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> deleteNotification(@PathVariable("id") Long id) {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long currentUserId = loginUser.getUser().getId();  // 获取当前登录用户ID

        boolean success = notificationService.deleteNotification(id, currentUserId);

        if (success) {
            return ResponseResult.success(true);
        } else {
            return ResponseResult.error("删除消息失败");
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/unread-count")
    public ResponseResult<Integer> getUnreadCount() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        Long currentUserId = loginUser.getUser().getId();  // 获取当前登录用户ID

        int count = notificationService.getUnreadCount(currentUserId);
        return ResponseResult.success(count);
    }

    /**
     * 管理员发送系统通知
     */
    @PostMapping("/system")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<Boolean> sendSystemNotification(@RequestBody SystemNotificationRequest request) {
        try {
            for (Long userId : request.getUserIds()) {
                notificationService.createNotification(
                        userId,
                        request.getTitle(),
                        request.getContent(),
                        "SYSTEM_NOTIFICATION",
                        null,
                        request.getTargetUrl()
                );
            }
            return ResponseResult.success(true);
        } catch (Exception e) {
            return ResponseResult.error("发送系统通知失败: " + e.getMessage());
        }
    }

    /**
     * 系统通知请求对象
     */
    static class SystemNotificationRequest {
        private String title;
        private String content;
        private String targetUrl;
        private Long[] userIds;

        // Getters and setters
        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public String getTargetUrl() {
            return targetUrl;
        }

        public void setTargetUrl(String targetUrl) {
            this.targetUrl = targetUrl;
        }

        public Long[] getUserIds() {
            return userIds;
        }

        public void setUserIds(Long[] userIds) {
            this.userIds = userIds;
        }
    }
}